package com.suitbim.commandserver.commandserver.manage;

import com.suitbim.commandserver.commandserver.util.HttpClientUtil;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URI;

@Component
public class FileManage {

//    private Semaphore fileDownLoadSemaphore = new Semaphore(3, true);

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Value("${redis-message-queue.revit-command}")
    private String revitQueueName;

    @Value("${redis-message-queue.navisworks-command}")
    private String navisworksQueueName;

    Logger log = LoggerFactory.getLogger(this.getClass());

    public void deleteFile(File file) {
        log.info("delete file:" + file.getAbsolutePath());
        boolean delete = file.delete();
        if (delete) log.info("file deleted");
    }

    public void downLoadFile(String url, String folder) throws Exception {

        //异步下载的方式可能存在遗漏一条任务的问题，但是增加数量能加快下载吗？
        //todo 尝试多线程下载有没有加速效果，理论上总体时间一样，但等待时间更加平均
//        log.info("file downLoad locked");
//        fileDownLoadSemaphore.acquire();
//
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                try {
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    fileDownLoadSemaphore.release();
//                }
//            }
//        };
//
//        threadPoolExecutor.submit(runnable);

        log.info("start download file:" + url);
        String[] split = url.split("/");
        HttpClientUtil.RequestBuilder requestBuilder = httpClientUtil.buildRequest().buildGet(new URI(url));
        HttpResponse response = requestBuilder.getResponse();
        requestBuilder.writeToFile(folder + "/" + split[split.length - 1]);
        log.info("file download success");

    }

    private boolean isRevitFile(String url) {
        return url.toLowerCase().trim().endsWith("rvt");
    }


}
